package cn.codergege.myspider.scheduler;

import cn.codergege.myspider.component.Request;
import cn.codergege.myspider.component.Response;
import cn.codergege.myspider.utils.MyspiderUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 调度器, 调度 request 和 result
 */
@Slf4j
public class Scheduler {
    private BlockingQueue<Request> requestQueue = new LinkedBlockingQueue<>();
    private BlockingQueue<Response> responseQueue = new LinkedBlockingQueue<>();

    public void addRequest(Request request) {
        try {
            this.requestQueue.put(request);
        } catch (InterruptedException e) {
            log.error("无法向请求队列放置 Request!");
        }
    }

    public void addRequests(List<Request> requests) {
        if(!MyspiderUtils.isEmpty(requests)) {
            requests.forEach(this::addRequest);
        }
    }

    public void addResponse(Response response) {
        try {
            this.responseQueue.put(response);
        } catch (InterruptedException e) {
            log.error("无法向响应队列放置 Response!");
        }
    }

    public boolean hasRequest() {
        return this.requestQueue.size() > 0;
    }

    public Request nextRequest() {
        try {
            return requestQueue.take();
        } catch (InterruptedException e) {
            log.error("无法从请求队列获取下一个 Request!");
            return null;
        }
    }

    public boolean hasResponse() {
        return this.responseQueue.size() > 0;
    }

    public Response nextResponse() {
        try {
            return responseQueue.take();
        } catch (InterruptedException e) {
            log.error("无法从响应队列中获取下一个 Response!");
            return null;
        }
    }
}
